using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Terra.Data.SeedData;

/// <summary>
/// 种子数据管理器
/// </summary>
public static class SeedDataManager
{
    private static readonly List<ISeedDataProvider> _providers = new();
    private static bool _initialized = false;

    /// <summary>
    /// 初始化种子数据提供者
    /// </summary>
    private static void InitializeProviders()
    {
        if (_initialized) return;

        var providerType = typeof(ISeedDataProvider);
        var types = Assembly.GetExecutingAssembly()
            .GetTypes()
            .Where(t => !t.IsAbstract && !t.IsInterface && providerType.IsAssignableFrom(t));

        foreach (var type in types)
        {
            if (Activator.CreateInstance(type) is ISeedDataProvider provider)
            {
                _providers.Add(provider);
            }
        }

        // 按优先级排序
        _providers.Sort((x, y) => x.Order.CompareTo(y.Order));
        _initialized = true;
    }

    /// <summary>
    /// 应用所有种子数据提供者
    /// </summary>
    /// <param name="modelBuilder">模型构建器</param>
    public static void ApplySeedData(ModelBuilder modelBuilder)
    {
        InitializeProviders();

        foreach (var provider in _providers)
        {
            provider.Configure(modelBuilder);
        }
    }
}